<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @example 三种情况
 *
 */
class Model_Fields extends Model_Database {

	protected $_type = array();
	protected $_field_type = array();

	public function __construct()
	{
		parent::__construct();
		/*
		$this->_field_type = array(
			'sex' => true,
			'area' => true,
			'vehicle' => true,
			'language' => true,
			'speciality' => true,
		);*/
		//the same one below
		//$_columns = $this->_db->list_columns('fields','type');
		//$_type = array_get_recursive($_columns,'type/options');
		$_type = DB::select('type')->from('fields')->group_by('type')->execute()->as_array('type', 'type');
		$this->_field_type = array_fill_keys($_type, TRUE);

		// 读取validate中的二重指向
		$_validate = (array)Kohana::$config->load('validate'); 
		$t = array_selector($_validate,'*/*/*/type');

		foreach ($t as $v1) 
			foreach ($v1 as  $v2) 
				foreach($v2 as $key => $value) 
					isset($value['type']) && $this->_type[$key] = $value['type'];
		$this->_type = array_merge($this->_field_type,$this->_type); //合并基础数据
	}

	public function get_origin_type()
	{
		return $this->_field_type;
	}

	public function get_fields_list($type = '')
	{
		$_fields_list = array();
		if (is_null($_fields_list = $this->get_cache('fields')))
		{
			$query = DB::select('*')->from('fields')->order_by('order');
			$t = $query->execute()->as_array();

			foreach ($t as $value)
				$_fields_list[ ($value['type']) ][ ($value['id']) ] = array_keyfilter($value,'text,id,extra');
			foreach ($this->_type as $key => $value) //补未赋值的项目
				if (!array_key_exists($key, $_fields_list)) //没有值
					$_fields_list[$key] = is_string($value) && isset($_fields_list[ $value ]) ? $_fields_list[ $value ] : array(); //可能是指向到某一type上
			$this->set_cache('fields',$_fields_list);
		}
		return !empty($type) ? $_fields_list[$type] : $_fields_list;
	}

	public function get_type_list()
	{
		$_columns = $this->_db->list_columns('fields','type');
		$type = array_get_recursive($_columns,'type/options');
		$comment = explode('\',\'', $_columns['comment']);
		return compact('type','comment');
	}

	public function fields_to_text($dataset,$parent_key = '',&$fields = array())
	{
		$result = array();
		if (!empty($dataset) && is_array($dataset))
		{
			$_fields = !empty($fields) ? $fields : $this->get_fields_list();

			foreach ($dataset as $key => $value)
			{
				$v = $value;
				$k = is_int($key) && !empty($parent_key) ? $parent_key : $key; //如果当前$key为数字(dataset里面字段名不可能为数字),就用父级的名称试试
				if (is_array($value))
					$v = $this->fields_to_text($value,$key,$_fields);
				elseif (array_key_exists($k, $_fields))
				{
					$v = array('id' => $value,'text' => '','type'=> $this->_type[$k]); //设置一个默认值，不然会在 PHP 5.4 中 Illegal string offset 'text'
					isset($_fields[$k][$value]) && $v = array('id' => $value,'text' => $_fields[$k][$value]['text'],'type' => $this->_type[$k]);
				}
				$result[$key] = $v;
			}
		}
		else
			$result = $dataset;
			
		return $result;
	}

	public function add($type,$text,$extra = '')
	{
		if (in_array($type,$this->_field_type))
		{
			$query = DB::select(array(DB::expr('MAX(`order`)'),'order'))->from('fields')->where('type','=',$type);
			$order = intval($query->execute()->get('order')) + 1;
			$query = DB::insert('fields',array('type','text','extra','order'))->values(array($type,$text,$extra,$order));
			$t = $query->execute();
			$id = array_shift($t);

			$this->delete_cache('fields');

			Model_Log::log(compact('id'));
			return $id;
		}
		return FALSE;
	}//

	public function get($id)
	{
		$query = DB::select('id','type','text','extra','order')->from('fields')->where('id','=',$id);
		return $query->execute()->current();
	}

	public function update($id, $text, $extra = NULL)
	{
		$set = array();
		$set['text']  = $text;
		!is_null($extra) && $set['extra']  = $extra;

		DB::update('fields')->set($set)->where('id','=',$id)->execute();

		$this->delete_cache('fields');

		Model_Log::log();
		return true;
	}

	public function delete($id)
	{
		//$_field = $this->get($id);
		//if (!empty($_field))
		//{
			DB::delete('fields')->where('id','=',$id)->execute();
			//DB::delete('member_fields')->where('value','=',$id)->and_where('type','=',$_field['type'])->execute();
			//if ($_field['type'] == 'area')
				//DB::delete('member_fields')->where('value','=',$id)->and_where('type','=','servearea')->execute();
		//}

		$this->delete_cache('fields');

		Model_Log::log();
		return TRUE;
	}

	public function move($original_id,$target_id,$move_type = 'next')
	{
		$src_node = $this->get($original_id);
		$target_node = $this->get($target_id);

		if (empty($src_node) || empty($target_node)) //不存在
			return FALSE;
		if ($src_node['type'] != $target_node['type']) //类别不同
			return FALSE;

		$order = $target_node['order'] + ($move_type == 'prev' ? 0 : 1);
		//将此Order后的子集全部加1
		DB::update('fields')->set(array('order' => DB::expr('`order` + 1')))->where('type','=',$target_node['type'])->and_where('order','>=',$order)->execute();
		//修改自身的Order
		DB::update('fields')->set(array('order'=>$order))->where('id','=',$original_id)->execute();

		$this->delete_cache('fields');

		Model_Log::log();
		return TRUE;
	}

	public function enum($type, $comment = NULL)
	{
		//ALTER TABLE `fields` CHANGE `type` `type` ENUM('fields_1','fields_2','fields_3') NOT NULL COMMENT '注释';
		$this->_db->query(Database::UPDATE, 'ALTER TABLE '.$this->_db->quote_table('fields').' CHANGE `type` `type` ENUM '.$this->_db->quote($type).' NOT NULL COMMENT \''.$this->_db->quote($comment).'\' ');
		
		$this->delete_cache('fields');

		Model_Log::log();
		return TRUE;
	}

}